﻿using System;
using System.IO;

namespace OverlakeServer_SOAP
{
    /// <summary>
    /// A class that implements logging of usage patterns.
    /// </summary>
    public static class Logger
    {
        static Logger()
        {
            //t_Elapsed(null, null);

            var t = new System.Timers.Timer(1000 * 60 * 20);  // Twenty Minutes     // Six hours
            t.Elapsed += new System.Timers.ElapsedEventHandler(t_Elapsed);
            t.Start();
        }

        static void t_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            InitWriter();
        }

        static void InitWriter()
        {
            string fileName = @"C:\OverlakeApp\Logs\" + DateTime.Now.ToString("yyyyMMdd-HHmmss") + ".log";

            while (writerLock) ;
            writerLock = true;
            if (writer != null)
            {
                writer.Flush();
                writer.Close();
            }
            writer = new StreamWriter(fileName);
            writerLock = false;
        }

        static bool writerLock = false;
        static StreamWriter writer;

        /// <summary>
        /// Log a login event.
        /// </summary>
        /// <param name="user">The user that logged in.</param>
        /// <param name="userAgent">The device from which they logged in.</param>
        /// <param name="ip">The ip of the user.</param>
        public static void LogLogin(string user, string userAgent, string ip)
        {
            if (writer == null)
                InitWriter();

            while (writerLock) ;
            writerLock = true;
            writer.WriteLine(DateTime.Now.ToString() + "," + user + "," + userAgent + "," + ip);
            writerLock = false;
        }
    }
}